package com.tulei.xiecheng;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;



public class XieCheng {


    public static void main(String[] args) throws Exception {
        URL url = new URL("https://flights.ctrip.com/international/search/api/search/batchSearch?v=0.26117753849297554");
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("POST");

        httpConn.setRequestProperty("accept", "application/json");
        httpConn.setRequestProperty("accept-language", "zh-CN,zh;q=0.9,en;q=0.8");
        httpConn.setRequestProperty("cache-control", "no-cache");
        httpConn.setRequestProperty("content-type", "application/json;charset=UTF-8");
        httpConn.setRequestProperty("cookie", "UBT_VID=1719897658182.72a2cSLYCZjz; GUID=09031136119211688714; MKT_CKID=1719897658372.tx760.hb06; _RF1=113.57.237.74; _RSG=lK46oGxy.2CUsMA9qox_YB; _RDG=28affe4661c6dd2f0a28c30f9a10cea3b9; _RGUID=c0bef3b4-3218-452f-b8bf-ef2d09296d9e; nfes_isSupportWebP=1; nfes_isSupportWebP=1; MKT_Pagesource=PC; _ubtstatus=%7B%22vid%22%3A%221719897658182.72a2cSLYCZjz%22%2C%22sid%22%3A1%2C%22pvid%22%3A20%2C%22pid%22%3A600001375%7D; _bfaStatusPVSend=1; _bfaStatus=send; Session=smartlinkcode=U130026&smartlinklanguage=zh&SmartLinkKeyWord=&SmartLinkQuary=&SmartLinkHost=; Union=AllianceID=4897&SID=130026&OUID=&createtime=1719900985&Expires=1720505785374; _pd=%7B%22_o%22%3A11%2C%22s%22%3A18%2C%22_s%22%3A1%7D; _abtest_userid=523d9524-9ac1-4fd0-b7af-52bc11ceac3a; _jzqco=%7C%7C%7C%7C1719897658901%7C1.748186183.1719897658385.1719900999781.1719902516046.1719900999781.1719902516046.0.0.0.10.10; cticket=C02F5DF56D97FF3223AF768251F2783B86E227F5AD3A491FB550C8078E22801D; login_type=0; login_uid=B4CDDAC972BB31515D592FB605B91014; DUID=u=1FF3B45C7A4D963705149FEDF3EC85F6&v=0; IsNonUser=F; AHeadUserInfo=VipGrade=0&VipGradeName=%C6%D5%CD%A8%BB%E1%D4%B1&UserName=%CD%BF%C0%DA&NoReadMessageCount=0; FlightIntl=Search=[%22WUH|%E6%AD%A6%E6%B1%89(WUH)|477|WUH|480%22%2C%22SHA|%E4%B8%8A%E6%B5%B7(SHA)|2|SHA|480%22%2C%222024-07-02%22%2C%222024-07-05%22]; _bfa=1.1719897658182.72a2cSLYCZjz.1.1719908595032.1719908598371.2.2.10320673304");
        httpConn.setRequestProperty("origin", "https://flights.ctrip.com");
        httpConn.setRequestProperty("priority", "u=1, i");
        httpConn.setRequestProperty("referer", "https://flights.ctrip.com/online/list/round-bjs-sha?depdate=2024-07-03_2024-07-06&cabin=y_s_c_f&adult=1&child=0&infant=0&containstax=1");
        httpConn.setRequestProperty("scope", "d");
        httpConn.setRequestProperty("sec-ch-ua", "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\"");
        httpConn.setRequestProperty("sec-ch-ua-mobile", "?0");
        httpConn.setRequestProperty("sec-ch-ua-platform", "\"Windows\"");
        httpConn.setRequestProperty("sec-fetch-dest", "empty");
        httpConn.setRequestProperty("sec-fetch-mode", "cors");
        httpConn.setRequestProperty("sec-fetch-site", "same-origin");
        httpConn.setRequestProperty("sign", "fae3c2c6ffa2f28246f78f5e14cb4e73");
        httpConn.setRequestProperty("token", "1001-common-mXdx6kIQBraqWXSW6gwZtYQ1x81jFDiF6YpSJkdjBLJDfrOSvqnwt8JzHwoLvm5vb8EQmEcoRpnEQOyaXin8WgMY7TKQAiNzyDXJnoWfLy3delmicHxGY55xSLE0NyH9R7gyXURaGvpfv6QWNhjOhw6QWN1JhLjbUv01vgwpSYXsWcYtUylNROTyLOizjNymYAqv9lR1mYU9RlcytnRD4vXBjG7v9DyalwXoJdtjz9RnsjLlY6ZIOpyPzYzhE1LYHZwLHJZ8ImLK0zEMAe69ILProFRZgjT0yhY7Mw3kr91yk6JlqvFfRLUWOkY9hy4BjZnEgsetzwdQYt9YS6yoceMaEThydNJbzjM6eU0JAZjHNy8Zw6geqMJDgyNqEtavqZyPhiU1j68Ecbj4LwQ4JdHRkDIQURpkyaYUZyBkKD9iNkJfhwGZY6mwSHyq1v4SYFbwAQefGjGde1Yb9wfMw3hRnpY9aEoQis0WNNK6YNHypzWsZEMgv4qemsYFNinSYhMjMDjZbrGYMbIGayDqrANeXkET7jopWcovQEH0RzYnLjPXKtTYncrLbKA7e05EN3WmSWfOwMw8YDhw5PissxXpRzUvZAYX3WXmelqRFcWZ9j1QWqoI9vBDRTYfGYzGJ6gwkBRpmv0kYF5WAce0aRZqWX9iskYUaYsZed");
        httpConn.setRequestProperty("transactionid", "03cabc37c3dc412c916a68d6e44902a5");
        httpConn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36");

        httpConn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
        writer.write("{\"flightWayEnum\":\"RT\",\"arrivalProvinceId\":1,\"extGlobalSwitches\":{\"useAllRecommendSwitch\":true,\"unfoldPriceListSwitch\":true,\"roundTabModeSwitch\":true,\"splitRoundFlightsSwitch\":false,\"splitRoundBuildUpSwitch\":false},\"arrivalCountryName\":\"中国\",\"infantCount\":0,\"cabin\":\"Y_S_C_F\",\"cabinEnum\":\"Y_S_C_F\",\"departCountryName\":\"中国\",\"flightSegments\":[{\"departureDate\":\"2024-07-03\",\"arrivalProvinceId\":2,\"arrivalCountryName\":\"中国\",\"arrivalCountryCode\":\"CN\",\"departureCityName\":\"北京\",\"departureCityCode\":\"BJS\",\"departureCountryName\":\"中国\",\"departureCountryCode\":\"CN\",\"arrivalCityName\":\"上海\",\"arrivalCityCode\":\"SHA\",\"departureCityTimeZone\":480,\"arrivalCountryId\":1,\"timeZone\":480,\"departureCityId\":1,\"departureCountryId\":1,\"arrivalCityTimeZone\":480,\"departureProvinceId\":1,\"arrivalCityId\":2},{\"departureDate\":\"2024-07-06\",\"arrivalProvinceId\":1,\"arrivalCountryName\":\"中国\",\"arrivalCountryCode\":\"CN\",\"departureCityName\":\"上海\",\"departureCityCode\":\"SHA\",\"departureCountryName\":\"中国\",\"departureCountryCode\":\"CN\",\"arrivalCityName\":\"北京\",\"arrivalCityCode\":\"BJS\",\"departureCityTimeZone\":480,\"arrivalCountryId\":1,\"timeZone\":480,\"departureCityId\":2,\"departureCountryId\":1,\"arrivalCityTimeZone\":480,\"departureProvinceId\":2,\"arrivalCityId\":1}],\"childCount\":0,\"segmentNo\":1,\"scope\":\"d\",\"adultCount\":1,\"extensionAttributes\":{\"LoggingSampling\":false,\"isFlightIntlNewUser\":false},\"transactionID\":\"03cabc37c3dc412c916a68d6e44902a5\",\"directFlight\":false,\"departureCityId\":1,\"isMultiplePassengerType\":0,\"noRecommend\":false,\"army\":\"\",\"flightWay\":\"D\",\"arrivalCityId\":1,\"departProvinceId\":1}");
        writer.flush();
        writer.close();
        httpConn.getOutputStream().close();

        InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                ? httpConn.getInputStream()
                : httpConn.getErrorStream();
        Scanner s = new Scanner(responseStream).useDelimiter("\\A");
        String json = s.hasNext() ? s.next() : "";

        ObjectMapper objectMapper = new ObjectMapper();

        List<FlightDetail> list = new ArrayList<>();
        JSONObject data = new JSONObject(json);
        JSONObject dataObject = data.getJSONObject("data");
        JSONArray flightItineraryListArray = dataObject.getJSONArray("flightItineraryList");
        for (int i = 0; i < flightItineraryListArray.length(); i++) {
            JSONObject flightItinerary = flightItineraryListArray.getJSONObject(i);
            if (flightItinerary.has("flightSegments")) {
                JSONArray flightSegments = flightItinerary.getJSONArray("flightSegments");
                JSONObject flightSegmentsJSONObject = flightSegments.getJSONObject(0);

                // 添加对 "flightList" 键的检查
                if (flightSegmentsJSONObject.has("flightList")) {
                    JSONArray flightList = flightSegmentsJSONObject.getJSONArray("flightList");
                    try {
                        JSONObject flightListJSONObject = flightList.getJSONObject(0);
                        FlightDetail flightDetail = objectMapper.readValue(flightListJSONObject.toString(), FlightDetail.class);
                        list.add(flightDetail);
                    } catch (JSONException | JsonProcessingException e) {
                        System.out.println("1111");
                    }
                } else {
                    System.out.println("Flight itinerary's flightSegments do not contain 'flightList' key, skipping...");
                }
            } else {
                System.out.println("Flight itinerary does not contain 'flightSegments' key, skipping...");
            }
        }

        String filePath = "D:\\Temp\\fligh.txt";
        try {
            // 如果文件不存在，则创建文件
            Files.createDirectories(Paths.get(filePath).getParent());
            Files.createFile(Paths.get(filePath));

            for (FlightDetail obj : list) {
                String jsonString = objectMapper.writeValueAsString(obj);
                Files.write(Paths.get(filePath), jsonString.getBytes(), StandardOpenOption.APPEND);
                Files.write(Paths.get(filePath), "\n".getBytes(), StandardOpenOption.APPEND);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
